package com.wl.index.Controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wl.bean.Result;
import com.wl.entity.Comments;
import com.wl.index.Biz.ICommentsBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/comments")
@CrossOrigin(origins = "*") // 允许所有来源，生产环境应限制为特定域名
public class CommentController {
    @Autowired
    private ICommentsBiz commentsBiz;

    /**
     * 获取帖子评论列表
     */
    @GetMapping("/list/{nid}")
    public Result getCommentsByNid(@PathVariable("nid") Integer nid) {
        System.out.println("nid="+nid);
        if (nid == null || nid <= 0) {
            return new Result(0, "帖子ID必须为正整数", null);
        }

        List<Map<String, Object>> comments = commentsBiz.getCommentsByUid(nid);
        System.out.println("正在查询nid为：" + nid + " 的评论");
        System.out.println("查询结果：" + comments);
        System.out.println("结果数量：" + (comments != null ? comments.size() : 0));

        return new Result(1, "评论获取成功", comments);
    }

    /**
     * 添加评论
     */
    @PostMapping("/add")
    public Result addComment(@RequestBody Map<String, Object> rawRequest) {
        System.out.println("原始请求体: " + rawRequest);
        System.out.println("UID值: " + rawRequest.get("uid")); // 专门打印uid
        System.out.println("UID类型: " + (rawRequest.get("uid") != null ? rawRequest.get("uid").getClass() : "null"));

        Comments comments = new ObjectMapper().convertValue(rawRequest, Comments.class);
        // 设置创建时间
        comments.setCreatAt(new Date());

        int result = commentsBiz.addComment(comments);
        if (result > 0){
            //获取新创建的评论ID
            int newCommentCid = comments.getCid();
            return new Result( 1,  "评论添加成功",  Map.of("cid",newCommentCid));
        } else {
            return new Result( 0,  "评论添加失败",  null);
        }
    }
}
